package com.example.lunbo;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.VideoView;

import com.example.lunbo.utils.PlayerUtils;

import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private static final int FLAG_NEXT = 10000;
    private MyHandler myHandler = new MainActivity.MyHandler(this);
    public RotationAdapter adapter;
    private int tempPosition = 0;
    private List<MediaDetailBean> mList = new ArrayList<MediaDetailBean>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerView = findViewById(R.id.recycler_view);
        String muPath = "android.resource://" + this.getPackageName() + "/" + R.raw.auy;

        adapter = new RotationAdapter(mList);

        //设置布局
        ViewPagerLayoutManager layoutManager = new ViewPagerLayoutManager(this);
        //横向布局
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(layoutManager);

        layoutManager.setOnViewPagerListener(new OnViewPagerListener() {
            @Override
            public void onInitComplete() {
                MediaDetailBean mediaDetailBean = adapter.getData().get(0);
                myHandler.removeCallbacksAndMessages(null);

                if (mediaDetailBean.getItemType() == 1) {
                    //判断第一条数据设置0
                    Message message = myHandler.obtainMessage();
                    message.what = FLAG_NEXT;
                    message.obj = 1;
                    long start = PlayerUtils.getInstance().start(MainActivity.this, muPath, new OnCompletionListener() {
                        @Override
                        public void onCompletion() {

                        }
                    });
                    myHandler.sendMessageDelayed(message, start);

                } else {
                    View viewByPosition = layoutManager.findViewByPosition(0);
                    if (viewByPosition != null) {
                        VideoView videoView = viewByPosition.findViewById(R.id.video_view);
                        videoView.setVideoPath(mediaDetailBean.getUri());
                        videoView.start();
                        PlayerUtils.getInstance().start(MainActivity.this, muPath, () -> videoView.setOnPreparedListener(mediaPlayer -> mediaPlayer.setVolume(1, 1)));

                        videoView.setOnPreparedListener(mediaPlayer -> mediaPlayer.setVolume(0f, 0f));
                        //判断第一条数据设置0
                        Message message = myHandler.obtainMessage();
                        message.what = FLAG_NEXT;
                        message.obj = 1;
                        myHandler.sendMessageDelayed(message, mediaDetailBean.getDuration());
                    }
                }

            }

            @Override
            public void onPageRelease(boolean isNext, int position) {

            }

            @Override
            public void onPageSelected(int position, boolean isBottom) {
                //下面那个就是滑动之后 返回的当前的下标
                PlayerUtils.getInstance().stop();
                MediaDetailBean mediaDetailBean = adapter.getData().get(position);
                myHandler.removeCallbacksAndMessages(null);
                tempPosition = position;
                if (mediaDetailBean.getItemType() == 2) {
                    View viewByPosition = layoutManager.findViewByPosition(position);
                    if (viewByPosition != null) {
                        VideoView videoView = viewByPosition.findViewById(R.id.video_view);
                        videoView.setVideoPath(mediaDetailBean.getUri());
                        videoView.start();

                        PlayerUtils.getInstance().start(MainActivity.this, muPath, new OnCompletionListener() {
                            @Override
                            public void onCompletion() {
                                String name = videoView.getClass().getName();
                                try {
                                    Field age = videoView.getClass().getDeclaredField("mMediaPlayer");
                                    age.setAccessible(true);
                                    MediaPlayer o = (MediaPlayer) age.get(videoView);
                                    o.setVolume(1, 1);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            }
                        });

                        videoView.setOnPreparedListener(mediaPlayer -> mediaPlayer.setVolume(0f, 0f));
                        //判断第一条数据设置0
                        Message message = myHandler.obtainMessage();
                        message.what = FLAG_NEXT;
                        tempPosition += 1;
                        message.obj = tempPosition;
                        myHandler.sendMessageDelayed(message, mediaDetailBean.getDuration());
                    }

                } else if (mediaDetailBean.getItemType() == 1) {
                    //判断第一条数据设置0
                    Message message = myHandler.obtainMessage();
                    message.what = FLAG_NEXT;
                    tempPosition += 1;
                    message.obj = tempPosition;
                    long start = PlayerUtils.getInstance().start(MainActivity.this, muPath, null);
                    myHandler.sendMessageDelayed(message, start);
                }
            }
        });
        recyclerView.setAdapter(adapter);

        initData();
    }


    private void initData() {


        for (int i = 0; i < 4; i++) {
            if (i % 2 == 1) {
                String path2 = "android.resource://" + this.getPackageName() + "/" + R.raw.video1;
                MediaDetailBean detailBean = new MediaDetailBean();
                detailBean.setType(2);
                detailBean.setUri(path2);
                MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
                mediaMetadataRetriever.setDataSource(this, Uri.parse(path2));
                String s = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
                detailBean.setDuration(Long.parseLong(s));
                mList.add(detailBean);
            } else {
                //图片
                String path1 = "android.resource://" + this.getPackageName() + "/" + R.raw.img;
                //视频
                //图片
                MediaDetailBean detailBean2 = new MediaDetailBean();
                detailBean2.setType(1);
                detailBean2.setUri(path1);
                detailBean2.setDuration(5000);
                mList.add(detailBean2);
            }
        }

        adapter.notifyDataSetChanged();
    }

    private static class MyHandler extends Handler {
        //        静态内部类+弱引用，防止内存泄漏
        private WeakReference<MainActivity> weakReference;

        public MyHandler(MainActivity activity) {
            this.weakReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //判断标识
            if (msg.what == FLAG_NEXT) {
                int obj = (int) msg.obj;
                //判断Activity是否存在
                if (weakReference.get() != null) {
                    if (weakReference.get().adapter.getData().size() == obj) {
                        obj = 0;
                    }
                    if (obj == 0) {
                        //取消动画
                        weakReference.get().recyclerView.scrollToPosition(obj);
                    } else {
                        //设置动画
                        weakReference.get().recyclerView.smoothScrollToPosition(obj);
                    }
                }
            }
        }
    }
}